﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Farkhod.QuickDataViewer
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo("LoggingConfiguration.config"));
        }

        private async void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                bool isDBConnected = false, needToShowConnStringWindow = true;
                ConnectionStringEditor connStringWindow;
                EnableComponents(false);
                do
                {
                    ShowMessageInStatusBar("Connecting to server...");
                    vbProgress.Visibility = System.Windows.Visibility.Visible;
                    isDBConnected = await GetDatabases();
                    if (!isDBConnected && needToShowConnStringWindow)
                    {
                        vbProgress.Visibility = System.Windows.Visibility.Hidden;
                        connStringWindow = new ConnectionStringEditor();
                        needToShowConnStringWindow = (bool)connStringWindow.ShowDialog();
                    }
                }
                while (!isDBConnected && needToShowConnStringWindow);
                if (!isDBConnected)
                {
                    ShowMessageInStatusBar("Unable to connect to server...");
                    return;
                }
                ShowMessageInStatusBar(string.Empty);
                vbProgress.Visibility = System.Windows.Visibility.Hidden;
                EnableComponents(true);
                await GetTables();
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private void EnableComponents(bool enable)
        {
            tbDatabases.IsEnabled = enable;
            cbDatabases.IsEnabled = enable;
            rbTables.IsEnabled = enable;
            rbViews.IsEnabled = enable;
            lsTablesViews.IsEnabled = enable;
        }

        private void ShowMessageInStatusBar(string message)
        {
            Dispatcher.Invoke(new Action(() => { tbMessage.Text = message; }));
        }

        private async void cbDatabases_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                CleanLstTablesViews();
                if (rbTables.IsChecked == true)
                    await GetTables();

                if (rbViews.IsChecked == true)
                    await GetViews();
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private void CleanLstTablesViews()
        {
            try
            {
                if (lsTablesViews != null)
                {
                    lsTablesViews.ItemsSource = null;
                    lsTablesViews.Items.Clear();
                }
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private async Task<bool> GetDatabases()
        {
            bool result = false;
            try
            {
                this.cbDatabases.ItemsSource = await DBManager.Instance.GetDBs();
                if (cbDatabases.Items.Count > 0)
                    cbDatabases.SelectedItem = DBManager.Instance.GetDBName();

                result = true;
            }
            catch (DbException)
            {
                ShowMessageInStatusBar("Unable to connect to server.");
                result = false;
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
                result = false;
            }
            return result;
        }

        private async Task GetTables()
        {
            try
            {
                if (cbDatabases.SelectedItem != null)
                {
                    DBManager.Instance.SetDBName(cbDatabases.SelectedItem.ToString());
                    lsTablesViews.ItemsSource = await DBManager.Instance.GetTables();
                }
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private async Task GetViews()
        {
            try
            {
                if (cbDatabases.SelectedItem != null)
                {
                    DBManager.Instance.SetDBName(cbDatabases.SelectedItem.ToString());
                    lsTablesViews.ItemsSource = await DBManager.Instance.GetViews();
                }
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private async void rbTables_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                rbViews.IsChecked = false;
                CleanLstTablesViews();
                if (rbTables.IsChecked == true && cbDatabases.Items.Count > 0)
                    await GetTables();
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private async void rbViews_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                rbTables.IsChecked = false;
                CleanLstTablesViews();
                if (rbViews.IsChecked == true && cbDatabases.Items.Count > 0)
                    await GetViews();
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private void lsTablesViews_MouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (lsTablesViews.SelectedItem != null)
                {
                    string selectedItem = (string)lsTablesViews.SelectedItem;
                    DBManager.Instance.SetDBName(cbDatabases.SelectedItem.ToString());
                    DataWindow dw = new DataWindow(selectedItem);
                    dw.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;
                    dw.Show();
                }
            }
            catch (Exception ex)
            {
                ShowMessageInStatusBar(ex.Message);
            }
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            Application.Current.Shutdown();
        }
    }
}

